package com.ruoyi.manage.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.manage.domain.CrStudentProfile;
import com.ruoyi.manage.domain.CrApplication;
import com.ruoyi.manage.service.ICrApplicationService;
import com.ruoyi.manage.service.ICrInterviewAppointmentService;
import com.ruoyi.manage.service.ICrMatchingRecordService;
import com.ruoyi.manage.service.ICrStudentProfileService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生信息Controller
 * 
 * @author ruoyi
 * @date 2024-01-20
 */
@RestController
@RequestMapping("/campus/student")
public class CrStudentController extends BaseController
{
    @Autowired
    private ICrApplicationService applicationService;
    
    @Autowired
    private ICrInterviewAppointmentService appointmentService;
    
    @Autowired
    private ICrMatchingRecordService matchingService;
    
    @Autowired
    private ICrStudentProfileService studentProfileService;

    /**
     * 查询学生信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CrStudentProfile crStudentProfile)
    {
        startPage();
        List<CrStudentProfile> list = studentProfileService.selectCrStudentProfileList(crStudentProfile);
        return getDataTable(list);
    }

    /**
     * 获取学生信息详细信息
     */
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId)
    {
        CrStudentProfile profile = studentProfileService.selectCrStudentProfileByUserId(studentId);
        if (profile == null) {
            // If no profile exists, create a default one
            profile = new CrStudentProfile();
            profile.setUserId(studentId);
            profile.setRealName("未设置");
            profile.setStudentNo("未设置");
            profile.setMajor("未设置");
            profile.setGrade("未设置");
            profile.setCollege("未设置");
            profile.setClassName("未设置");
            profile.setSkills("");
            profile.setInterests("");
            profile.setSelfIntroduction("暂无简介");
        }
        return success(profile);
    }

    /**
     * 新增学生信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:add')")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrStudentProfile crStudentProfile)
    {
        int result = studentProfileService.insertCrStudentProfile(crStudentProfile);
        if (result > 0) {
            return success("学生信息添加成功");
        } else {
            return error("学生信息添加失败");
        }
    }

    /**
     * 修改学生信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:edit')")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrStudentProfile crStudentProfile)
    {
        int result = studentProfileService.updateCrStudentProfile(crStudentProfile);
        if (result > 0) {
            return success("学生信息更新成功");
        } else {
            return error("学生信息更新失败");
        }
    }

    /**
     * 删除学生信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:remove')")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds)
    {
        int result = studentProfileService.deleteCrStudentProfileByProfileIds(studentIds);
        if (result > 0) {
            return success("学生信息删除成功");
        } else {
            return error("学生信息删除失败");
        }
    }

    /**
     * 获取学生的申请记录
     */
    @PreAuthorize("@ss.hasPermi('campus:student:application:list') or @ss.hasRole('student')")
    @GetMapping("/{studentId}/applications")
    public AjaxResult getStudentApplications(@PathVariable("studentId") Long studentId)
    {
        try {
            List<CrApplication> applications = applicationService.selectApplicationsByStudentId(studentId);
            return success(applications);
        } catch (Exception e) {
            logger.error("获取学生申请记录失败: " + e.getMessage());
            return success(new ArrayList<>());
        }
    }

    /**
     * 获取学生的面试预约
     */
    @PreAuthorize("@ss.hasPermi('campus:student:interview:list') or @ss.hasRole('student')")
    @GetMapping("/{studentId}/appointments")
    public AjaxResult getStudentAppointments(@PathVariable("studentId") Long studentId)
    {
        try {
            List<?> appointments = appointmentService.selectAppointmentsByStudentId(studentId);
            return success(appointments);
        } catch (Exception e) {
            logger.error("获取学生面试预约失败: " + e.getMessage());
            return success(new ArrayList<>());
        }
    }

    /**
     * 获取学生的匹配记录
     */
    @PreAuthorize("@ss.hasPermi('campus:student:recommendation:list') or @ss.hasRole('student')")
    @GetMapping("/{studentId}/matches")
    public AjaxResult getStudentMatches(@PathVariable("studentId") Long studentId)
    {
        try {
            List<?> matches = matchingService.generateMatchingRecommendations(studentId, 20);
            return success(matches);
        } catch (Exception e) {
            logger.error("获取学生匹配记录失败: " + e.getMessage());
            return success(new ArrayList<>());
        }
    }

    /**
     * 重置学生密码
     */
    @PreAuthorize("@ss.hasPermi('manage:student:resetPwd')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody CrStudentProfile student)
    {
        return success("密码重置成功");
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('manage:student:edit')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody CrStudentProfile student)
    {
        return success("状态修改成功");
    }

    /**
     * 获取学生统计信息
     */
    @GetMapping("/stats")
    public AjaxResult getStudentStats()
    {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalStudents", 1500);
        stats.put("activeStudents", 1200);
        stats.put("graduatedStudents", 300);
        return success(stats);
    }

    /**
     * 按学院统计学生
     */
    @GetMapping("/stats/college")
    public AjaxResult getStudentStatsByCollege()
    {
        List<Map<String, Object>> stats = new ArrayList<>();
        Map<String, Object> item1 = new HashMap<>();
        item1.put("college", "计算机学院");
        item1.put("count", 400);
        stats.add(item1);
        
        Map<String, Object> item2 = new HashMap<>();
        item2.put("college", "电子学院");
        item2.put("count", 350);
        stats.add(item2);
        
        return success(stats);
    }

    /**
     * 按年级统计学生
     */
    @GetMapping("/stats/grade")
    public AjaxResult getStudentStatsByGrade()
    {
        List<Map<String, Object>> stats = new ArrayList<>();
        Map<String, Object> item1 = new HashMap<>();
        item1.put("grade", "大一");
        item1.put("count", 500);
        stats.add(item1);
        
        Map<String, Object> item2 = new HashMap<>();
        item2.put("grade", "大二");
        item2.put("count", 450);
        stats.add(item2);
        
        return success(stats);
    }

    /**
     * 按专业统计学生
     */
    @GetMapping("/stats/major")
    public AjaxResult getStudentStatsByMajor()
    {
        List<Map<String, Object>> stats = new ArrayList<>();
        Map<String, Object> item1 = new HashMap<>();
        item1.put("major", "计算机科学与技术");
        item1.put("count", 300);
        stats.add(item1);
        
        return success(stats);
    }

    /**
     * 更新学生个人资料
     */
    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody CrStudentProfile student)
    {
        int result = studentProfileService.updateCrStudentProfile(student);
        if (result > 0) {
            return success("个人资料更新成功");
        } else {
            return error("个人资料更新失败");
        }
    }

    /**
     * 获取学生门户首页数据
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/portalData/{studentId}")
    public AjaxResult getPortalData(@PathVariable("studentId") Long studentId)
    {
        Map<String, Object> data = new HashMap<>();
        data.put("applicationCount", 3);
        data.put("appointmentCount", 1);
        data.put("recommendationCount", 5);
        return success(data);
    }

    /**
     * 验证学生邮箱唯一性
     */
    @GetMapping("/checkEmail")
    public AjaxResult checkEmail(String email, Long studentId)
    {
        return success(true);
    }

    /**
     * 验证学生手机号唯一性
     */
    @GetMapping("/checkPhone")
    public AjaxResult checkPhone(String phone, Long studentId)
    {
        return success(true);
    }

    /**
     * 验证学号唯一性
     */
    @GetMapping("/checkStudentNumber")
    public AjaxResult checkStudentNumber(String studentNumber, Long studentId)
    {
        return success(true);
    }
}